from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.oauth.models import OAuthQQUser
from apps.users.models import User

'''
我们所做的都是为了一个openid
openid 是此网站上唯一对应用户身份的标识

'''
from django.http import HttpResponseBadRequest
class QQLoginView(View):
    def get(self,request):
        code=request.GET.get('code')
        state=request.GET.get('status')
        if code is None:
            return HttpResponseBadRequest('没有ｃｏｄｅ')
        from meiduo_mall import settings
        from QQLoginTool.QQtool import OAuthQQ
        oauthqq=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state
                        )
        token = oauthqq.get_access_token(code)
        openid = oauthqq.get_open_id(token)
        try:
            qquser=OAuthQQUser.objects.get(openid=openid)
        except:
            return render(request, 'oauth_callback.html',context={'openid':openid})

        else:
            login(request,qquser.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username',qquser.user.username,max_age=24*3600)
            return response

    def post(self,request):
        # 接收数据
        mobile=request.POST.get('mobile')
        pwd=request.POST.get('pwd')
        sms_code=request.POST.get('sms_code')
        openid=request.POST.get('openid')
        # 验证数据　（上课省略）

        # 根据手机号进行用户信息查询　user
        try:
            user=User.objects.get(mobile=mobile)
        except:
            # 如果不存在，说明用户手机没有注册过，我们就以这个手机号注册一个用户
            user=User.objects.create_user(username=mobile,
                                          password=pwd,
                                          mobile=mobile)

        else:
            # 如果存在则需要验证密码
            if user.check_password(pwd):
                return HttpResponseBadRequest('密码错误')
        # 绑定openid 和 user
        OAuthQQUser.objects.create(user=user,openid=openid)
        # 登陆（设置登陆状态，设置cookie，跳转到首页）
        login(request,user)

        response=redirect(reverse('contents:index'))

        response.set_cookie('username',user.username, max_age=24*3600)
        return response

